//
//  AppDelegate.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/8/31.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 导航控制器 和 tabbar 设置，最要在所有操作之前设置
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.rootViewController = defaultViewController()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: GXSwitchRootViewControllerNotification, object: nil)
        
        window?.makeKeyAndVisible()
    
        
        setupNetwork()
    
        return true
    }
    
    
     func switchRootViewController(notification: NSNotification) {
        let message = notification.object
        
       let vc = (message == nil) ? MainViewController() : WelcomeViewController()
        
        UIApplication.sharedApplication().keyWindow?.rootViewController = vc
        
    }
    
    private func defaultViewController() -> UIViewController {
    
      // 首先判断用户是否登录
        if UserAccountViewModel.sharedUserAccount.accessToken != nil {
            
            return isNewVersion() ?  NewFeatureViewController() : WelcomeViewController()
            
        }else {
            return MainViewController()
        }
        
    }
    
     // MARK: - 判断是否是最新的版本
    private func isNewVersion()->Bool {
        
        // 1.获取版本的信息
        let NewboundleVersion =  Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)
    
        // 2.获取历史的版本信息
        // 设置一个key
        let versionKey = "com.hqu.weibo.version"
        // 获得旧的版本信息没有就返回0
        let oldBoundleVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        // 3.保存版本的信息
        NSUserDefaults.standardUserDefaults().setDouble(NewboundleVersion!, forKey: versionKey)
        
        // 4.比较版本的信息
        return NewboundleVersion > oldBoundleVersion
    }
    
    
    /// 设置网络指示器
    private func setupNetwork() {
        // 设置网络指示器，一旦设置，发起网络请求，会在状态栏显示菊花，指示器只负责 AFN 的网络请求，其他网络框架不负责
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        
        // 设置缓存大小 NSURLCache －> GET 请求的数据会被缓存
        // 缓存的磁盘路径: /Library/Caches/(application bundle id)
        // MATTT，内存缓存是 4M，磁盘缓存是 20M
        // 提示：URLSession 只有 dataTask 会被缓存，downloadTask / uploadTask 都不会缓存
        let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
    }


    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

